package com.lottery.game.runner;

import com.lottery.game.common.utils.DateUtils;
import com.lottery.game.core.modules.entity.game.GameRoom;
import com.lottery.game.core.modules.service.app.BetService;
import com.lottery.game.websocket.RobotSpeak;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.task.TaskExecutor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * Runner 程序启动后自动运行 -> GameThreadRunner代替
 *
 * @author zhuiyv
 * @date 2018-06-21
 */
@Slf4j
//@Component
@Deprecated
public class CloudGameRunner implements ApplicationRunner {

	@Autowired
	private BetService betService;

	@Autowired
	private TaskExecutor taskExecutor;

	@Autowired
	private RobotSpeak robotSpeak;

	public Map<String, RoomManager> roomThreadMap = new HashMap<String, RoomManager>();

	@Override
	public void run(ApplicationArguments args) throws Exception {

		log.info("当前时间：{}，主线程runner启动。。", DateUtils.getNowDateString());

		// 获取不同房间类型
		List<GameRoom> roomTypeList = betService.queryRoomTypeList();
		for (GameRoom roomType : roomTypeList) {
			log.info("{} 类型 房间处理线程启动。。", roomType.getRoomLotteryTicketType());
			RoomManager roomManager = new RoomManager(taskExecutor, robotSpeak, betService, roomType, false, null,
					null);
			roomThreadMap.put(buildKey(roomType.getRoomLotteryTicketType()), roomManager);
			roomManager.start();
		}
	}

	/**
	 *
	 * @param typeId
	 * @param roomType
	 */
	public void restart(GameRoom roomType, String typeId, String expect, Integer initTime) {
		RoomManager roomManager = new RoomManager(taskExecutor, robotSpeak, betService, roomType, true, expect,
				initTime);

		String mapKey = buildKey(typeId);
		// 停掉旧的线程
		RoomManager oldThread = roomThreadMap.get(mapKey);
		if (oldThread != null) {
			oldThread.userStop();
		}
		// 启动新的线程
		roomThreadMap.put(mapKey, roomManager);
		roomManager.start();
	}

	/**
	 * 构建一个带前缀的key
	 *
	 * @param typeId
	 * @return
	 */
	private String buildKey(String typeId) {
		String perStr = "roomType_";
		return perStr + typeId;
	}

}
